package com.bihua.web.controller.shop;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bihua.common.constant.CacheConstants;
import com.bihua.common.core.controller.BaseController;
import com.bihua.common.core.domain.R;
import com.bihua.common.exception.user.CaptchaException;
import com.bihua.common.exception.user.CaptchaExpireException;
import com.bihua.common.utils.StringUtils;
import com.bihua.common.utils.file.MimeTypeUtils;
import com.bihua.common.utils.redis.RedisUtils;
import com.bihua.shop.helper.ShopLoginHelper;
import com.bihua.shop.service.ITShopUserService;
import com.bihua.system.domain.vo.SysOssVo;
import com.bihua.system.service.ISysConfigService;
import com.bihua.system.service.ISysOssService;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import lombok.RequiredArgsConstructor;

/**
 * @author wuzhong
 * @date 2023年09月20日 16:45
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/shop/shopUser")
public class ShopUserController  extends BaseController {
    private final ITShopUserService iTShopUserService;
    private final ISysConfigService configService;
    private final ISysOssService iSysOssService;
    /**
     * 修改密码
     *
     * @param password 密码
     */
    @PutMapping("/updatePwd")
    public R<Void> updatePwd(String password, String code, String uuid) {
        String captchaEnabledStr = configService.selectConfigByKey("shop.account.captchaEnabled");
        boolean captchaEnabled =true;
        if (StringUtils.isNotEmpty(captchaEnabledStr)) {
            captchaEnabled = Convert.toBool(captchaEnabledStr);
        }
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha(code, uuid);
        }
        if (iTShopUserService.resetUserPwd(ShopLoginHelper.getUserId(), BCrypt.hashpw(password)) > 0) {
            return R.ok();
        }
        return R.fail("修改密码异常，请联系管理员");
    }
    /**
     * 头像上传
     *
     * @param avatarfile 用户头像
     */
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, Object>> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
        Map<String, Object> ajax = new HashMap<>();
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            SysOssVo oss = iSysOssService.upload(avatarfile);
            String avatar = oss.getUrl();
            if (iTShopUserService.updateUserAvatar(getUserId(), avatar)) {
                ajax.put("imgUrl", avatar);
                return R.ok(ajax);
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }
    /**
     * 校验验证码
     *
     * @param code     验证码
     * @param uuid     唯一标识
     */
    private void validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
}
